<script setup lang="tsx">
import { ref, reactive, unref, shallowRef, provide, markRaw, type Component } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Table } from '@/components/Table'
import { ElCollapseTransition } from 'element-plus'
import Write from './component/Write.vue'
import Detail from './component/Detail/index.vue'
import { useTable } from '@/hooks/web/useTable'
import { BaseButton } from '@/components/Button'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { getListApi, delApi, type Row } from '@/api/document'

defineOptions({
  name: 'Purchase'
})

const comId = reactive({
  Write: markRaw(Write),
  Detail: markRaw(Detail)
})

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    type: 'selection'
  },
  {
    field: 'no',
    label: '单据编号',
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'order_status',
    label: '单据状态',
    search: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '待审核',
            value: 1
          },
          {
            label: '待签收',
            value: 2
          },
          {
            label: '待入库',
            value: 3
          },
          {
            label: '审核拒绝',
            value: 4
          },
          {
            label: '已完成',
            value: 5
          }
        ]
      }
    },
    form: { hidden: true },
    detail: { hidden: true },
    formatter: (cellValue) => {
      return cellValue.order_status_text
    }
  },
  {
    field: 'goods_type_count',
    label: '商品种类',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'goods_count',
    label: '商品总数',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'create_time',
    label: '单据提交时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD'
      }
    },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'update_time',
    label: '单据完成时间',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'action',
    label: '操作',
    width: '260px',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    slots: {
      default: ({ row }) => {
        return (
          <>
            <BaseButton type="primary" onClick={() => detailAction(row)}>
              详情
            </BaseButton>
          </>
        )
      }
    }
  }
])
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)
const ids = ref<string[]>([])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.count
    }
  },
  fetchDelApi: async () => {
    const res = await delApi({ id: unref(ids).join(',') })
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const showCollapse = ref(false)
let currentAction = shallowRef()
let currentRow = reactive<any>({})
const action = (component: Component, id?: number) => {
  id ? (currentRow.id = id) : undefined
  currentAction.value = component
  if (showCollapse.value === false) showCollapse.value = true
}
const detailAction = async (row) => {
  action(comId['Detail'], row.id)
}
const delLoading = ref(false)

const delData = async (row: Row | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: Row) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const closeCollapse = () => {
  showCollapse.value = false
}

provide('currentRow', currentRow)
</script>

<template>
  <ContentWrap title="采购单列表">
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="action(comId['Write'])">新增</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">删除</BaseButton>
    </div>

    <el-collapse-transition>
      <component
        :is="currentAction"
        :key="currentRow.id"
        @close="closeCollapse"
        @get-list="getList"
        v-if="showCollapse"
      />
    </el-collapse-transition>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{ total }"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
